package com.guoxue.action.front;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guoxue.domain.BookConfigVo;
import com.guoxue.domain.ChapterConfigVo;
import com.guoxue.domain.CollectAndTransferVo;
import com.guoxue.domain.ExpertReadingVo;
import com.guoxue.domain.FollowsVo;
import com.guoxue.domain.GoodBookRecordVo;
import com.guoxue.domain.IOSDeviceVo;
import com.guoxue.domain.PersonPushVo;
import com.guoxue.domain.RecordConfigVo;
import com.guoxue.domain.TapesRecordsVo;
import com.guoxue.domain.TapesShareVo;
import com.guoxue.domain.TotalInfoVo;
import com.guoxue.domain.UserVo;
import com.guoxue.model.ExpertRead;
import com.guoxue.service.IBookConfigService;
import com.guoxue.service.IChapterConfigService;
import com.guoxue.service.ICollectAndTransferService;
import com.guoxue.service.IExpertReadingService;
import com.guoxue.service.IFollowsService;
import com.guoxue.service.IGoodBookRecordService;
import com.guoxue.service.IIOSDeviceService;
import com.guoxue.service.IPersonPushService;
import com.guoxue.service.IRecordConfigService;
import com.guoxue.service.ITapesRecordsService;
import com.guoxue.service.ITapesShareService;
import com.guoxue.service.ITotalInfoService;
import com.guoxue.service.IUserService;
import com.guoxue.util.LoadConfigProperties;
import com.guoxue.util.LoggerUtil;
import com.guoxue.util.OSSUtil;
import com.guoxue.util.OtherUtils;
import com.guoxue.util.PushUtil;

/**
 * 接收并返回录音的收藏和转发
 */
@Controller
@RequestMapping("/User")
public class CollectAndTransferAction extends BaseAction {

	@Resource
	private IUserService userService;
	@Resource
	private ICollectAndTransferService collectAndTransferService;
	@Resource
	private ITapesRecordsService tapesRecordsVoService;
	@Resource
	private ITapesShareService tapesShareService;
	@Resource
	private IBookConfigService bookService;
	@Resource
	private ITotalInfoService totalInfoService;
	@Resource
	private OSSUtil oss;
	@Resource
	private IExpertReadingService expertReadingService;
	@Resource
	private IGoodBookRecordService goodBookRecordService;
	@Resource
	private IChapterConfigService chapterConfigService;
	@Resource
	private IRecordConfigService recordConfigService;
	@Resource
	private IPersonPushService personPushService;
	@Resource
	private IFollowsService followsService;
	@Resource
	private IIOSDeviceService IOSDeviceService;
	@Resource
	private PushUtil pushUtil;
	@Resource
	private ITapesRecordsService tapesService;
	
	/**
	 * 提交转发或者收藏记录
	 * 
	 * @param req
	 * @param resp
	 * @param type
	 *            (1.转发2.收藏)
	 * @param flag
	 *            作品key
	 * @param uid
	 *            自己id
	 * @param tapeId
	 *            作品id
	 * @param chapterId
	 *            章节id
	 * @param chaptereEndId
	 *            章节结束id(佳作特有的)
	 * @param chapter
	 *            章节名称
	 * @param userComment
	 * @param tapesUid
	 *            被转发或收藏人Id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/collectAndTransferCommit")
	public JSON collectAndTransferCommit(HttpServletRequest req, HttpServletResponse resp, Integer type, String flag,
			Integer uid, String tapeId, String chaptereEndId, String chapterId, String chapter, String userComment,
			String tapesUid) {
		try {
			if (isEmpty(flag)) {
				return Message(ERROR, "未指定作品key", null);
			}
			if (isEmpty(tapeId)) {
				return Message(ERROR, "未指定作品id", null);
			}
			if (null == type) {
				return Message(ERROR, "未指定类型", null);
			} else {
				if (type > 2 || type < 1) {
					return Message(ERROR, "指定类型错误", null);
				}
			}
			if (null == uid) {
				return Message(ERROR, "未提交用户Id", null);
			}
			if (isEmpty(tapesUid)) {
				return Message(ERROR, "未提交被转发或收藏人Id", null);
			}
			if (isEmpty(chaptereEndId)) {
				// TODO 是否添加作品id查询
				Long tapesToatl = tapesRecordsVoService.getTapesRecordsTotal(Integer.valueOf(tapesUid), flag);
				if (tapesToatl <= 0) {
					return Message(ERROR, "请先上传再进行转发或者收藏", null);
				}
			}
			// (1.转发2.收藏)
			Long count = collectAndTransferService.getCollectAndTransferTotal(uid, type, tapeId);
			if (count >= 100) {
				// 转发、收藏为何要设置上限呢？
				if (type == 1) {
					return Message(ERROR, "转发已经达到上限", null);
				} else {
					return Message(ERROR, "收藏已经达到上限", null);
				}
			}
			Long count2 = collectAndTransferService.getCollectAndTransferTotal(uid, tapesUid, type, tapeId);
			if (count2 >= 1) {
				// 转发、收藏为何要设置上限呢？
				if (type == 1 ) {
					return Message(ERROR, "已转发该作品", null);
				} else {
					return Message(ERROR, "已收藏该作品", null);
				}
			}
			CollectAndTransferVo collectAndTransfer = new CollectAndTransferVo();
			collectAndTransfer.setCommitTime(OtherUtils.getCurrentDate());
			collectAndTransfer.setFlag(flag);
			collectAndTransfer.setSysflag(0);
			collectAndTransfer.setType(type);
			collectAndTransfer.setUid(uid);
			collectAndTransfer.setTapesUid(tapesUid);
			collectAndTransfer.setTapeId(tapeId);
			collectAndTransfer.setChapter(chapter);
			collectAndTransfer.setChapterId(chapterId);
			if (null != chaptereEndId) {
				collectAndTransfer.setChaptereEndId(chaptereEndId);
			}
			collectAndTransfer.setUserComment(userComment);
			collectAndTransferService.saveCollectAndTransfer(collectAndTransfer);
			TapesShareVo  tapesShareVo =tapesShareService.getTapesShareByTid(Integer.valueOf(tapeId), 0);
			tapesShareVo.setShareCount(tapesShareVo.getShareCount()+1);
			tapesShareService.saveTapesShare(tapesShareVo);
			//推送消息给自己的好友
			UserVo user = userService.getUserByKey(uid);
			String message = "";
			if (type == 1) {
				if (null != chaptereEndId) {
					ExpertReadingVo e = expertReadingService.getExpertReading(tapeId);
					message = "***"+user.getNickName()+"转发***"+e.getWriter()+"的作品《***"+e.getBookName()+"》，点击查看";
				}else{
					UserVo user2 = userService.getUserByKey(Integer.valueOf(tapesUid));
					message = "***"+user.getNickName()+"转发***"+user2.getNickName()+"的作品《***"+chapter+"》，点击查看";
				}
			} else {
				if (null != chaptereEndId) {
					ExpertReadingVo e = expertReadingService.getExpertReading(tapeId);
					message = "***"+user.getNickName()+"收藏***"+e.getWriter()+"的作品《***"+e.getBookName()+"》，点击查看";
				}else{
					UserVo user2 = userService.getUserByKey(Integer.valueOf(tapesUid));
					message = "***"+user.getNickName()+"收藏***"+user2.getNickName()+"的作品《***"+chapter+"》，点击查看";
				}
			}
			PersonPushVo personPush = new PersonPushVo();
			personPush.setUserId(String.valueOf(uid));
			personPush.setCreateTime(OtherUtils.getCurrentDate());
			personPush.setTapesId(tapeId);
			personPush.setContent(message);
			personPushService.savePersonPush(personPush);
			//推送消息
			List<FollowsVo> followsList = followsService.getFollowedList(uid);
			if(followsList.size() > 0){
				List<String> IOSDeviceList = new ArrayList<String>();
				for(FollowsVo f:followsList){
					IOSDeviceVo  IOSDevice = IOSDeviceService.getIOSDevice(f.getFollowed(),1);
					if(null != IOSDevice){
						IOSDeviceList.add(IOSDevice.getDeviceToken());
					}
				}
				if(IOSDeviceList.size() > 0){
					pushUtil.sendPush(IOSDeviceList, message, false, null);
				}
			}
			if (null == chaptereEndId) {
				if (type == 1) {
					return Message(SUCCESS, "转发成功", null);
				} else {
					return Message(SUCCESS, "收藏成功", null);
				}
			}else{
				if (type == 1) {
					return Message(SUCCESS, "佳作转发成功", null);
				} else {
					return Message(SUCCESS, "佳作收藏成功", null);
				}
			}
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "您的收藏或转发异常");
		}
	}
	/**
	 * 获取某个用户转发和收藏的作品
	 * 
	 * @param req
	 * @param resp
	 * @param type
	 *            1.转发2.收藏
	 * @param uid
	 *            用户id
	 * @param start
	 *            开始条数
	 * @param totalCount
	 *            取几条
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/collectAndTransferList")
	public JSON collectAndTransferList(HttpServletRequest req, HttpServletResponse resp, Integer type, Integer userId,
			Integer start, Integer totalCount,String date) {
		try {
			if (type == null) {
				return Message(ERROR, "未指定类型", null);
			} else {
				if (!type.equals(1) && !type.equals(2)) {
					return Message(ERROR, "指定类型错误", null);
				}
			}
			if (userId == null) {
				return Message(ERROR, "未提交用户id", null);
			}
			if (isEmpty(date)){
				return Message(ERROR, "未提交时间", null);
			}
			JSONObject json = new JSONObject();
			List<CollectAndTransferVo> CollectAndTransferVoList = new ArrayList<CollectAndTransferVo>();
			if (date.equals("0")){
				CollectAndTransferVoList = collectAndTransferService.getCollectAndTransferList(userId, type, start, totalCount);
			} else {
				CollectAndTransferVoList = collectAndTransferService.getCollectAndTransferList(userId, type, start, totalCount,date);
			}
			if (!date.equals("0")){
				if(CollectAndTransferVoList==null||CollectAndTransferVoList.isEmpty()){
					return Message(ERROR, "没有更多了··", null);
				}
			}
			JSONArray tapesArray = new JSONArray();
			String path = req.getContextPath();
			String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + "/";
			for (CollectAndTransferVo c : CollectAndTransferVoList) {
				JSONObject tapesInfo = new JSONObject();
				if (null != c.getTapeId()) {
					TapesShareVo share = tapesShareService.getTapesShareByTid(Integer.valueOf(c.getTapeId()), 0);
					if (isEmpty(c.getChaptereEndId())) {
						tapesInfo.put("goodBook", null);
						if (null != c.getChapterId()) {
							BookConfigVo book = bookService.getBookByChapterId(Integer.valueOf(c.getChapterId()));
							tapesInfo.put("belongBook", book.getBookName());
						}
						
						UserVo user = userService.getUserByKey(userId);
						if (user == null) {
							json.put("transferTotal", 0);
							json.put("collectTotal", 0);
						} else {
							Long collectTotal = collectAndTransferService.getMyCollectAndTransferTotal(userId, 2);
							Long transferTotal = collectAndTransferService.getMyCollectAndTransferTotal(userId,1);
							json.put("transferTotal", transferTotal);
							json.put("collectTotal", collectTotal);
						}
						// 转发或者收藏(1.转发2.收藏)
						TotalInfoVo total = totalInfoService.getInfoByUid(Integer.valueOf(c.getTapesUid()));
						if (total == null) {
							total = new TotalInfoVo();
							total.setUid(user.getId());
							tapesInfo.put("follow", 0);
							tapesInfo.put("listened", 0);
							totalInfoService.saveOrUpateInfo(total);
						} else {
							tapesInfo.put("follow", total.getFollow());
							tapesInfo.put("follower", total.getBeFollowed());
							tapesInfo.put("listened", total.getListened());
						}
						Integer tapesUid = Integer.valueOf(c.getTapesUid());
						UserVo user1 = userService.getUserByKey(tapesUid);
						tapesInfo.put("headUrl",isEmpty(user1.getImgUrl()) ? null: oss.getUrl(bucket, user1.getImgUrl(),new Date(new Date().getTime() + 3600 * 1000 * 12)));
						tapesInfo.put("userId", user1.getId());
						tapesInfo.put("userName", user1.getNickName());
						tapesInfo.put("personSignature", user1.getPersonSignature());
					} else {
						ExpertReadingVo expertReading = expertReadingService.getExpertReading(c.getTapeId());
						tapesInfo.put("headUrl",isEmpty(expertReading.getPhoto1()) ? null: oss.getUrl(bucket, expertReading.getPhoto1(),new Date(new Date().getTime() + 3600 * 1000 * 12)));
						tapesInfo.put("userId", c.getTapesUid());
						tapesInfo.put("userName", expertReading.getWorkReader());
						tapesInfo.put("belongBook", expertReading.getBookName());
						tapesInfo.put("follow", 0);
						tapesInfo.put("listened", 0);
						String url = isEmpty(expertReading.getPhoto1()) ? null: oss.getUrl(bucket, expertReading.getPhoto1(),new Date(new Date().getTime() + 3600 * 1000 * 12));
						expertReading.setPhoto1(url);
						JSONArray array = new JSONArray();
						if(!isEmpty(expertReading.getPhoto2())){
							array.add(isEmpty(expertReading.getPhoto2())?null:oss.getUrl(bucket, expertReading.getPhoto2(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
						}
						if(!isEmpty(expertReading.getPhoto3())){
							array.add(isEmpty(expertReading.getPhoto3())?null:oss.getUrl(bucket, expertReading.getPhoto3(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
						}
						if(!isEmpty(expertReading.getPhoto4())){
							array.add(isEmpty(expertReading.getPhoto4())?null:oss.getUrl(bucket, expertReading.getPhoto4(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
						}
						if(!isEmpty(expertReading.getPhoto5())){
							array.add(isEmpty(expertReading.getPhoto5())?null:oss.getUrl(bucket, expertReading.getPhoto5(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
						}
						if(!isEmpty(expertReading.getPhoto6())){
							array.add(isEmpty(expertReading.getPhoto6())?null:oss.getUrl(bucket, expertReading.getPhoto6(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
						}
						if(!isEmpty(expertReading.getPhoto7())){
							array.add(isEmpty(expertReading.getPhoto7())?null:oss.getUrl(bucket, expertReading.getPhoto7(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
						}
						if(!isEmpty(expertReading.getPhoto8())){
							array.add(isEmpty(expertReading.getPhoto8())?null:oss.getUrl(bucket, expertReading.getPhoto8(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
						}
						if(!isEmpty(expertReading.getPhoto9())){
							array.add(isEmpty(expertReading.getPhoto9())?null:oss.getUrl(bucket, expertReading.getPhoto9(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
						}
						if(!isEmpty(expertReading.getPhoto10())){
							array.add(isEmpty(expertReading.getPhoto10())?null:oss.getUrl(bucket, expertReading.getPhoto10(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
						}
						ExpertRead expertRead = new ExpertRead(array, expertReading);
						GoodBookRecordVo goodBookRecord = goodBookRecordService.getGoodBookRecord(expertReading.getWorkId());
						if (null != goodBookRecord) {
							expertRead.setCharpterId(String.valueOf(goodBookRecord.getCharpterId()));
						}
						ChapterConfigVo ch = chapterConfigService.getChapterConfig(expertReading.getBeginChapterId(), expertReading.getEndChapterId());
						RecordConfigVo r = recordConfigService.getRecordConfig(ch.getBeginWordId(), ch.getEndWordId());
						expertRead.setFile(r.getFile());
						tapesInfo.put("goodBook", expertRead);
					}
					tapesInfo.put("chapterId", c.getChapterId());
					tapesInfo.put("chapterName", c.getChapter());
					tapesInfo.put("tapesName", c.getFlag());
					tapesInfo.put("commitTime", c.getCommitTime());
					tapesInfo.put("tapesUid", c.getTapesUid());
					tapesInfo.put("tapeId", c.getTapeId());
					tapesInfo.put("collectAndTransferId", c.getId());
					TapesRecordsVo tapesRecordsVo = tapesRecordsVoService.getTapesById(Integer.valueOf(c.getTapeId()));
					if(null != tapesRecordsVo){
						tapesInfo.put("compent", isEmpty(tapesRecordsVo.getUserComment()) ? null : tapesRecordsVo.getUserComment());
					}else{
						tapesInfo.put("compent",null);
					}
					tapesInfo.put("shareUrl", basePath);
					if (share != null) {
						tapesInfo.put("commentCount", share.getCommentCount());
						tapesInfo.put("gifts", share.getTotalGifts());
						tapesInfo.put("listened", share.getTotalListend());
						tapesInfo.put("shareCount", share.getShareCount());
					} else {// 若未查询到对应记录则生成一条对应记录存放数据库
						tapesInfo.put("commentCount", 0);
						tapesInfo.put("gifts", 0);
						tapesInfo.put("listened", 0);
						tapesInfo.put("shareCount", 0);
						share = new TapesShareVo();
						share.setTapesId(Integer.valueOf(c.getTapeId()));
						tapesShareService.saveTapesShare(share);
					}
					tapesArray.add(tapesInfo);
				}
			}
			List<TapesRecordsVo> tapes = tapesService.findByUidAndStatus(userId, 0);
			Long collectTotal = collectAndTransferService.getMyCollectAndTransferTotal(userId, 2);
			Long transferTotal = collectAndTransferService.getMyCollectAndTransferTotal(userId, 1);
			json.put("transferTotal", transferTotal);
			json.put("collectTotal", collectTotal);
			if (tapesArray.size() > 0) {
				json.put("tapesTotal", tapes.size());
				json.put("tapes", tapesArray);
			} else {
				if(start < 1){
					json.put("tapesTotal", tapes.size());
					/*json.put("transferTotal", "0");
					json.put("collectTotal", "0");*/
					json.put("tapes", new JSONArray());
				}
			}
			json.put("time", OtherUtils.getCurrentDate());
			return Message(SUCCESS, "获取数据成功", json);
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "获取数据失败");
		}
	}

	/**
	 * 删除收藏或转发的作品
	 * 
	 * @param req
	 * @param resp
	 * @param collectAndTransferId
	 * @param uid
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/deleteCollectAndTransfer")
	public JSON deleteCollectAndTransfer(HttpServletRequest req, HttpServletResponse resp, Integer collectAndTransferId,
			Integer uid) {
		try {
			if (uid == null) {
				return Message(ERROR, "未提交用户id", null);
			}
			if (collectAndTransferId == null) {
				return Message(ERROR, "未提交collectAndTransferId", null);
			}
			CollectAndTransferVo collectAndTransfer = collectAndTransferService
					.getCollectAndTransfer(collectAndTransferId, uid);
			if (collectAndTransfer != null) {
				collectAndTransferService.deleteCollectAndTransfer(collectAndTransferId, uid);
				return Message(SUCCESS, "删除数据成功", null);
			} else {
				return Message(ERROR, "数据不存在", null);
			}
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "删除数据失败");
		}
	}

}
